<template>
	<view class="audioBox">
		<view class="" @click="playAudio">
			<m-icon v-if="state" class="circle" size="110" type="audio_paly" />
			<m-icon v-if="!state" size="110" type="audio_stop" />
		</view>
	</view>
</template>

<script>
	export default {
		name: "m-audio",
		props: {
			url: {
				type: String,
				default: () => {
					return ''
				}
			},
			// 是否自动播放
			autoplay: {
				type: Boolean,
				default: true,
			},
			// 是否循环播放
			loop: {
				type: Boolean,
				default: true,
			},
		},
		data() {
			return {
				src: this.url,
				innerAudioContext: null, // 播放实例
				state: false, //  播放状态  false暂停   true播放
			};
		},
		watch: {},
		computed: {
			aaa() {
             console.log('aaa');
			 return 111;
			}
		},
		mounted() {
			this.initAudio()
		},
		methods: {
			initAudio() {
				this.innerAudioContext = uni.createInnerAudioContext();
				this.state = this.autoplay;
				this.innerAudioContext.autoplay = this.autoplay; //设置是否自动播放
				this.innerAudioContext.loop = this.loop; // 是否循环播放
				this.innerAudioContext.obeyMuteSwitch = false; //是否遵循系统静音开关，当此参数为 false 时，即使用户打开了静音开关，也能继续发出声音，默认值 true
				this.innerAudioContext.src = this.src; //音频的url
				this.innerAudioContext.onPlay(() => {
					console.log('播放!');
				});
				this.innerAudioContext.onPause(() => {
					console.log('暂停播放!');
				});
				this.innerAudioContext.onEnded(() => {
					console.log('播放结束!');
				});
			},
			// 点击播放事件
			playAudio() {
				this.state = !this.state;
				if (this.state) {
					this.innerAudioContext.play(); //播放
				} else {
					this.innerAudioContext.pause(); //暂停
				}
			},
		},
		// 组件销毁 同时销毁音频
		destroyed() {
			if (this.innerAudioContext) {
				this.innerAudioContext.destroy();
			}
		},
	};
</script>

<style lang="scss" scoped>
	.audioBox {
		display: inline-block;
		position: relative;
	}

	.circle {
		animation: rotate 10s infinite linear;
	}

	@keyframes rotate {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>